package com.li.springbootproject.domain.properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.StandardServletEnvironment;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 2021/12/14 19:41
 */
@Component
@PropertySource(value = {"classpath:test/one.properties", "classpath:test/two.properties"}, encoding = "utf-8")
public class TestProperties {

    @Autowired
    private Environment environment;

    private Map<String, String> oneMap = new HashMap<>();

    private Map<String, String> twoMap = new HashMap<>();


    /**
     * 初始化配置 Bean
     *
     * @return
     */
    @Bean
    public TestProperties initTestProperties() {
        TestProperties testProperties = new TestProperties();
        MutablePropertySources propertySources = ((StandardServletEnvironment) environment).getPropertySources();
        Map<String, String> tempMapOne = new HashMap<>();
        Map<String, String> tempMapTwo = new HashMap<>();
        testProperties.setOneMap(tempMapOne);
        testProperties.setTwoMap(tempMapTwo);
        for (org.springframework.core.env.PropertySource<?> propertySource : propertySources) {
            if (propertySource.getName().contains("one.properties")) {
                Object source = propertySource.getSource();
                if (source instanceof Map) {
                    Map<String, String> map = (Map) source;
                    for (Map.Entry<String, String> o : map.entrySet()) {
                        tempMapOne.put(o.getKey(), o.getValue());
                    }
                }
            } else if (propertySource.getName().contains("two.properties")) {
                Object source = propertySource.getSource();
                if (source instanceof Map) {
                    Map<String, String> map = (Map) source;
                    for (Map.Entry<String, String> o : map.entrySet()) {
                        tempMapTwo.put(o.getKey(), o.getValue());
                    }
                }
            }
        }
        return testProperties;
    }

    public Map<String, String> getOneMap() {
        return oneMap;
    }

    public void setOneMap(Map<String, String> oneMap) {
        this.oneMap = oneMap;
    }

    public Map<String, String> getTwoMap() {
        return twoMap;
    }

    public void setTwoMap(Map<String, String> twoMap) {
        this.twoMap = twoMap;
    }
}
